<?php
namespace app\index\controller;

use think\Controller;


class Login extends controller
{
    //微信小程序登陆
    public function index()
    {   
        
        $code    = input('code');
        
        $wechat = db('wxapp_config')->find();

        $url     = "https://api.weixin.qq.com/sns/jscode2session?appid={$wechat['appid']}&secret={$wechat['secret']}&js_code={$code}&grant_type=authorization_code";
     
        $wxapp_user      = json_decode(file_get_contents($url),true);//获取用户openid与session_key

        $wxapp_user['session_id'] = $update_info['session_id'] = getRandCode(20);
        
        unset($wxapp_user['expires_in']);
       
        $update_result = $insert_result = 0;

        //默认没有绑定手机号
        if($result = db('user')->where('openid',$wxapp_user['openid'])->find()){
            $update_info['last_visit_time'] = time();
            $update_info['visit_times']     = (int)$result['visit_times']+1;
            $update_result = db('user')->where('openid',$wxapp_user['openid'])->update($update_info);
            //监测该用户是否正在使用共享球杆
            if($lock_info = db('lock')->where('user_id',$result['id'])->find()){

                $club_id                  = db('box')->where('id',$lock_info['box_id'])->value('club_id');
                $lock_info['club_number'] = db('club')->where('id',$club_id)->value('club_number');
                $data['lock_info'] = $lock_info;

                if($charge_id = db('charge_log')->where(array( 'user_id' =>$result['id'],'end_time' => 0 ,'lock_id'  => $lock_info['id']))->value('id')){
                    $data['charge_id'] = $charge_id;
                }
            }
            //检测用户今天是否获取每日红包
            

        }else{
            $wxapp_user['last_visit_time'] = $wxapp_user['create_time'] = time();
            $insert_result = db('user')->insert($wxapp_user);
        }
        //获取用户的信息
        $data['user_info'] = db('user')->where('openid',$wxapp_user['openid'])->field('mobile,deposit,id')->find();

        if($update_result || $insert_result){
            //每日红包
            if(!model('Redpacket')->isGetDailyRedpacket($data['user_info']['id'])){
                //添加每日红包
                $redpacket_price = (float)getRandomRedpacket();
               
                if(model('Redpacket')->giveUserRedpacket($data['user_info']['id'],2,$redpacket_price)){
                    $data['daily_redpacket_price'] = $redpacket_price;
                }
                
            }

            //添加战力记录
            model('Force')->addUserForceStatistics($data['user_info']['id']);

            $data['session_id'] = $wxapp_user['session_id'];
            $data['state'] = 1;
            $data['info']  = '登陆成功！';
        }else{
            $data['state'] = 0;
            $data['state'] = '登陆失败！';
        }
            return json($data);
    }    
   
}
